package com.hqd.jjvm.classformat.attributeinfo;

import com.hqd.jjvm.classformat.ClassFile;
import com.hqd.jjvm.util.HexStrTransformUtil;
import lombok.Getter;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.List;

@Getter
@NoArgsConstructor
public class LocalVariableTable extends AttributeInfo {
	private Integer localVariableTableLength;
	private List<LocalVariable> localVariableList;

	public LocalVariableTable(Integer localVariableTableLength, List<LocalVariable> localVariableList) {
		this.localVariableTableLength = localVariableTableLength;
		this.localVariableList = localVariableList;
	}

	class LocalVariable {
		private Integer startPc;
		private Integer length;
		private Integer nameIndex;
		private Integer descriptorIndex;
		private Integer index;

		public LocalVariable(Integer startPc, Integer length, Integer nameIndex, Integer descriptorIndex, Integer index) {
			this.startPc = startPc;
			this.length = length;
			this.nameIndex = nameIndex;
			this.descriptorIndex = descriptorIndex;
			this.index = index;
		}
	}

	public LocalVariableTable(Integer attributeNameIndex, Integer attributeLength, Integer localVariableTableLength, List<LocalVariable> localVariableList) {
		super(attributeNameIndex, attributeLength);
		this.localVariableTableLength = localVariableTableLength;
		this.localVariableList = localVariableList;
	}

	@Override
	protected LocalVariableTable newAttributeInfo(Integer attributeNameIndex, Integer attributeLength, ClassFile classFile) {
		this.localVariableTableLength = HexStrTransformUtil.parseHexToInt(classFile.readU2());
		List<LocalVariable> localVariables = new ArrayList<>(localVariableTableLength);
		for (int i = 0; i < localVariableTableLength; i++) {
			Integer startPc = HexStrTransformUtil.parseHexToInt(classFile.readU2());
			Integer length = HexStrTransformUtil.parseHexToInt(classFile.readU2());
			Integer nameIndex = HexStrTransformUtil.parseHexToInt(classFile.readU2());
			Integer descriptorIndex = HexStrTransformUtil.parseHexToInt(classFile.readU2());
			Integer index = HexStrTransformUtil.parseHexToInt(classFile.readU2());
			localVariables.add(new LocalVariable(startPc, length, nameIndex, descriptorIndex, index));
		}
		this.localVariableList = localVariables;
		return this;
	}
}
